package org.example.user.controller;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("secKill")
public class SecKillTest1 {
    private static final String buyAndSell = "-- 参与秒杀的用户集合\n" +
            "local join_key = KEYS[1]\n" +
            "-- 库存\n" +
            "local stock_key = KEYS[2]\n" +
            "-- 当前用户\n" +
            "local uid = ARGV[1]\n" +
            "-- 检查当前用户是否参与过这个活动\n" +
            "local has_buy = redis.call(\"sismember\", join_key, uid)\n" +
            "-- 如果没有参与过\n" +
            "if(tonumber(has_buy)==0)\n" +
            "then\n" +
            "-- 预扣库存\n" +
            "local stock = redis.call(\"decr\",stock_key)\n" +
            "-- 如果还有库存\n" +
            "if(tonumber(stock) >= 0)\n" +
            "then\n" +
            "-- 将用户添加到已参加活动的集合中\n" +
            "redis.call(\"sadd\", join_key, uid)\n" +
            "-- 返回1表示可以参加秒杀，后续进行订单处理\n" +
            "return 1\n" +
            "else\n" +
            "-- 返回-1表示因为没有库存不能参加秒杀\n" +
            "return -1\n" +
            "end\n" +
            "else\n" +
            "-- 返回-3表示已经参与过活动\n" +
            "return -3\n" +
            "end";
    @Autowired
    private RedisTemplate redisTemplate;


    //秒杀活动初始化

    @RequestMapping("init")
    public void init() {
        int hid = 1;
        Set keys = redisTemplate.keys("pbw*");
        redisTemplate.delete(keys);
        redisTemplate.opsForValue().set("pbw.stock_" + hid, 10);
        redisTemplate.opsForValue().set("pbw.sk.stock_" + hid, 10);
        redisTemplate.opsForSet().add("pbw.sk.hd_" + hid, 0);
    }

    @RequestMapping("buy/{hid}/{uid}")
    public boolean buy(@PathVariable long hid, @PathVariable long uid) {
        System.out.println("user_id=" + uid + " hid=" + hid);
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setResultType(Long.class);
        script.setScriptText(buyAndSell);
        List<String> keys = Lists.newArrayList("pbw.sk.hd_" + hid, "pbw.sk.stock_" + hid);
        Long result = (Long) redisTemplate.execute(script, keys, uid);
        System.out.println("lua脚本的执行结果为： " + result);
        return result > 0;
    }


}
